package com.eroly.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.eroly.common.GlobalSt;
import com.eroly.domain.User;
import com.eroly.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

public class ReqResFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(ReqResFilter.class);
    private final static String[] URIENDS = new String[]
            {".css",".js",".html",".jpg",".jpeg",".png",".pdf",".doc",".docx"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if(!StringUtil.isEmpty(requestURI) && requestURI.contains(".ico") || requestURI.contains("ImgCode")){
            filterChain.doFilter(request,response);
            return;
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(GlobalSt.USER_INFO);
        String userPhone = null;
        if(user!=null){
            userPhone = user.getUserPhone();
        }
        Map parameterMap = request.getParameterMap();

        logger.info("parameterMap:{}",parameterMap.toString());
        HashMap hashMap = new HashMap<>();
        Set set = parameterMap.keySet();
        for (Object o : set) {
            Object o1 = parameterMap.get(o);
            if(o1 instanceof String[]){
                String[] o11 = (String[]) o1;
                List<String> strings = Arrays.asList(o11);
                hashMap.put(o,strings);
            }else {
                hashMap.put(o,o1);
            }
        }
        logger.info("parameterHashMap:{}",hashMap.toString());
        logger.info(userPhone+"请求的URI{},Method:{}", requestURI, request.getMethod(),
                "\n"+userPhone+"请求报文:{}",JSONUtils.toJSONString(hashMap));

        //转换成代理类
        ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse) response);
        filterChain.doFilter(request,wrapperResponse);

        //获取返回值
        byte[] content = wrapperResponse.getContent();
        //判断是否有值
        if (content.length > 0) {
            if(!requestURIEndWith(requestURI)){
                String str = new String(content, "UTF-8");
                //打印响应
                logger.info(userPhone+"响应报文:{}", str);
//                String ciphertext = null;
//
//                try {
//                    //......根据需要处理返回值
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                //把返回值输出到客户端
//                ServletOutputStream out = response.getOutputStream();
//                out.write(ciphertext.getBytes());
//                out.flush();
//                out.close();
            }

            filterChain.doFilter(request,response);
        }
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }

    private boolean requestURIEndWith(String requestURI){
        if (!StringUtil.isEmpty(requestURI)) {
            if (requestURI.lastIndexOf(".")!=-1) {
                String substring = requestURI.substring(requestURI.lastIndexOf("."), requestURI.length());
                return Arrays.asList(URIENDS).contains(substring);
            }
        }
        return false;
    }
}
